<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function test(){
        $list = Db::name('data_table')->select();
        foreach ($list as $item){
            //获取人员信息
            $user = Db::name('data_user')->where('d_id',$item['id'])->select();
            Db::name('data_table') ->where('id',$item['id'])->update(['today_number'=>count($user)]);
            Db::name('floor') ->where('id',$item['f_id'])->update(['people'=>count($user)]);
        }
    }
    
    
    /**
     * 获取楼栋
     * */
    public function get_building(){
        $list = Db::name('building')->order('weigh','desc') ->select();
        $this->success('成功',$list,200);
    }
    /**
     * 获取单元
     * */
    public function get_unit(){
        $b_id = $this->request->param('b_id','');
        $where = [];
        if($b_id){
            $where['b_id'] = $b_id;
        }
        $list = Db::name('unit')->where($where)->order('weigh','desc') ->select();
        $this->success('成功',$list,200);
    }
    /**
     * 获取楼层
     * */
    public function get_floor(){
        $u_id = $this->request->param('u_id','');
        $where = [];
        if($u_id){
            $where['u_id'] = $u_id;
        }
        $list = Db::name('floor')->where($where)->order('weigh desc,id asc') ->group('floor') ->column('floor');
        $this->success('成功',$list,200);
    }

    /**
     * 获取房号
     * */
    public function get_house(){
        $u_id = $this->request->param('u_id','');
        $floor = $this->request->param('floor','');
        if(!$floor) {
            $this->error('请选择楼层','',201);
        }
        if(!$u_id) {
            $this->error('请选择单元','',201);
        }
        $where['u_id'] = $u_id;
        $where['floor'] = $floor;
        $list = Db::name('floor')->where($where)->order('weigh','desc') ->select();
        $this->success('成功',$list,200);
    }
    /**
     *   根据房号获取填写的用户信息
     * */
    public function get_user(){
        $f_id = $this->request->param('f_id','');
        if(!$f_id) {
            $this->error('请选择房号','',201);
        }
        //获取已经登记id
        $data_ids = Db::name('data_table')->where('f_id',$f_id)->column('id');
        $list = Db::name('data_user')->whereIn('d_id',$data_ids)->field('name,sex,card_no,phone')->group('card_no')->select();
        $this->success('成功',$list,200);
    }
    /**
     * 数据填报
     * */
    public function add_data(){
        $u_id = $this->request->param('u_id',0);
        $b_id = $this->request->param('b_id',0);
        $f_id = $this->request->param('f_id',0);
        $number = $this->request->param('number',1);
        $detail = $this->request->param('detail','');
        $type = $this->request->param('type','');
        $user_info = $this->request->param('user_info/a','');
        if(!$f_id || !$u_id || !$b_id) {
            $this->error('请选择户号','',201);
        }
        if(!$number) {
            $this->error('请选择居住人数','',201);
        }
        if(!$type) {
            $this->error('请选择产权类型','',201);
        }
        if(!$user_info) {
            $this->error('请输入用户信息','',201);
        }
        //判断是否已经申报
        //获取今天的时间戳
        $start_time = strtotime(date('Y-m-d',time()));
        $end_time =time();
        $card_nos = [];
        $today_number = 0;//登记人数
        foreach ($user_info as $key=>$item){

            $user_info[$key]['is_check'] =0;
            if(!isset($item['name']) || !$item['name']){
                $this->error('请填写姓名','',201);
            }
            if(!isset($item['sex']) || !$item['sex']){
                $this->error('请选择性别','',201);
            }
            if(!isset($item['card_no']) || !$item['card_no']){
                $this->error('请填写身份证号','',201);
            }
            if(!isset($item['phone']) || !$item['phone']){
                $this->error('请填写联系电话','',201);
            }
            if(!isset($item['time']) || !$item['time']){
                $this->error('请选择最后一次核酸时间','',201);
            }
            //判断身份证号码
            $is_true = $this->isCreditNo($item['card_no']);
            if(!$is_true){
                $this->error($item['name'].'身份证号码错误，请重新填写','',201);
            }
            //判断重复提交
            if(in_array($item['card_no'],$card_nos)){
                $this->error($item['name'].'已存在，请勿重复登记','',201);
            }
            $card_nos[] = $item['card_no'];
            //判断今天是否登记
            $is_check = Db::name('data_user') ->where('card_no',$item['card_no'])->whereTime('createtime','between',[$start_time,$end_time])->value('id');
            if($is_check){
                $user_info[$key]['is_check'] =1;//标记为已登记
            }else{
                $today_number ++;//增加登记人数
            }
        }

        Db::startTrans();
        $result = $res1 =true;
        try {
            //如果居住人数大于之前登记人数  则更新登记人数
            $floor_number = Db::name('floor')->where('id',$f_id)->value('people');
            if(floatval($number) > floatval($floor_number)){
                $res = Db::name('floor')->where('id',$f_id)->update(['people'=>$number]);
                if($res === false){
                    $result = false;
                }
            }
            $data = [
                'u_id' =>$u_id,
                'b_id' =>$b_id,
                'f_id' =>$f_id,
                'number' =>$number,
                'today_number' =>count($user_info),
                'type' =>$type,
                'detail' =>$detail,
                'createtime' =>time(),
            ];
            //判断该房号今天是否已经申报
            $is_check = Db::name('data_table')->where('f_id',$f_id) ->whereTime('createtime','between',[$start_time,$end_time])->value('id');
            if($is_check){
                $data_id = $is_check;
                //修改今天登记人数
                $data['today_number'] += $today_number;
                $res1 = Db::name('data_table') ->where('id',$data_id) ->update($data);
                if($res1 === false){
                    $result = false;
                }
            }
            else{
                $data_id = Db::name('data_table') ->insertGetId($data);
            }
            $user_data = [];
            foreach ($user_info as $item){
                $item['d_id'] = $data_id;
                $item['time'] = strtotime($item['time']);
                $item['createtime'] = time();
                if($item['is_check'] == 0){
                    unset($item['is_check']);
                    $user_data[] = $item;
                }
            }
            if($user_data){
                $re2 = Db::name('data_user') ->insertAll($user_data);
                if($re2  === false){
                    $result = false;
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(),'',201);
        }
        if ($result === false) {
            $this->error('填报失败','',201);
        }
        //获取该房号当日的登记记录
        $list = Db::name('data_user')->where('d_id',$data_id)->whereTime('createtime','between',[$start_time,$end_time])->select();
        foreach ($list as &$item){
            $item['time'] = date('m-d',$item['time']);
        }
        $this->success('成功',$list,200);

    }

    /**
     * 校验身份证号码格式是否正确
     * @param string $idcard
     * @return bool
     */
    protected  function isCreditNo($idcard)
    {
        $idcard = strtoupper($idcard);
        if (!preg_match('#^\d{17}(\d|X)$#', $idcard)) {
            return false;
        }
        // 判断出生年月日的合法性(解决号码为666666666666666666也能通过校验的问题)
        $birth = substr($idcard, 6, 8);
        if ($birth < "19000101" || $birth > date("Ymd")) {
            return false;
        }
        $year = substr($birth, 0, 4);
        $month = substr($birth, 4, 2);
        $day = substr($birth, 6, 2);
        if (!checkdate($month, $day, $year)) {
            return false;
        }
        // 校验身份证格式(mod11-2)
        $check_sum = 0;
        for ($i = 0; $i < 17; $i++) {
            // $factor = (1 << (17 - $i)) % 11;
            $check_sum += $idcard[$i] * ((1 << (17 - $i)) % 11);
        }
        $check_code = (12 - $check_sum % 11) % 11;
        $check_code = $check_code == 10 ? 'X' : strval($check_code);
        if ($check_code !== substr($idcard, -1)) {
            return false;
        }
        return true;
    }
}
